// vuex 的使用  详情参考官网 https://uniapp.dcloud.io/vue-vuex
import {
	HttpUrl
} from "./index.js"
const baseURL = HttpUrl
export default class Request {
	http(param) {
		// 请求参数
		var url = param.url,
			method = param.method,
			header = {},
			data = param.data || {},
			token = param.token || "",
			hideLoading = param.hideLoading || false,
			loadingShown = false,
			requestCount = 0,
			loadingDelayTime = 500,
			loadingTimer = null

		//拼接完整请求地址
		const requestUrl = baseURL + url
		//拼接完整请求地址（根据环境切换）
		// var requestUrl = operate.api() + url;

		//请求方式:GET或POST(POST需配置
		// header: {'content-type' : "application/x-www-form-urlencoded"},)
		let tokens = uni.getStorageSync("englishToken")

		if (method) {
			method = method.toUpperCase() //小写改为大写
			if (method == "POST") {
				header = {
					"content-type": "application/x-www-form-urlencoded"
				}
			} else {
				header = {
					"content-type": "application/json"
				}
			}
			header.token = tokens
		}
		//加载圈
		requestCount++

		if (!hideLoading) {
			loadingTimer = setTimeout(() => {
				uni.showLoading({
					title: "加载中..."
				})
				loadingShown = true
			}, loadingDelayTime)
		} 

		// 返回promise
		return new Promise((resolve, reject) => {
			// 请求
			uni.request({  
				url: requestUrl, 
				data: data, 
				method: method,
				header: header,
				success: (res) => {
					// 判断 请求api 格式是否正确

					if (res.data.code !== 1) {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
					} 
					if (res.data.code === 201) {
						uni.redirectTo({
							url: "/pages/login/login"
						})
						uni.removeStorageSync("englishToken")
					}
					// 将结果抛出 
					resolve(res.data)
				},
				//请求失败
				fail: (e) => {
					uni.showToast({
						title: e.data.msg,
						icon: "none"
					})
					resolve(e.data)
				},
				//请求完成
				complete() {
					//隐藏加载
					requestCount--
					clearTimeout(loadingTimer)
					// console.log(requestCount, "requestCount", loadingShown)

					if (!hideLoading && requestCount === 0 && loadingShown) {
						uni.hideLoading()
						loadingShown = false
					}
					resolve()
					return
				}
			})
		})
	}
}